package start;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

public class Producer {
    private static final String HOST = "47.108.48.236";
    private static final int PORT = 5672;
    private static final String VIRTUAL_HOST = "test";
    private static final String USER_NAME = "admin";
    private static final String PASSWORD = "admin";
    public static void main(String[] args) throws IOException, TimeoutException {
        // 创建连接工厂
        ConnectionFactory factory = new ConnectionFactory();
        // 设置参数
        factory.setHost(HOST);
        factory.setPort(PORT);
        factory.setVirtualHost(VIRTUAL_HOST);
        factory.setUsername(USER_NAME);
        factory.setPassword(PASSWORD);
        // 创建连接
        Connection connection = factory.newConnection();
        // 创建 channel
        Channel channel = connection.createChannel();
        /**
         * 声明队列
         * queue: 队列名称
         * durable：是否持久化，true：持久化队列存盘，服务器重启后消息不会丢失
         * exclusive：是否独占，仅限于此连接(Connection 关闭时，是否删除队列)
         * autoDelete: 是否自动删除, 当没有 Consumer 时，是否自动删除
         * arguments：相关参数
         */
        channel.queueDeclare("hello", true, false, false, null);
        // 发送消息
        String msg = "hello";
        /**
         * 通过 channel 发送消息到队列中
         * exchange：交换机名称，简单模式下，交换机使用默认的 ""
         * routingKey：路由名称, 简单模式下为队列名称
         * props：配置信息
         * body: 发送的数据
         */
        channel.basicPublish("", "hello", null, msg.getBytes());
        System.out.println("消息发送成功");
        // 释放资源
        channel.close();
        connection.close();
    }
}
